package cn.snmp.mutual.org.opennms.protocols.snmp;

import java.io.*;

import cn.snmp.mutual.org.opennms.protocols.snmp.asn1.AsnDecodingException;
import cn.snmp.mutual.org.opennms.protocols.snmp.asn1.AsnEncoder;
import cn.snmp.mutual.org.opennms.protocols.snmp.asn1.AsnEncodingException;

public class SnmpOctetString implements SnmpSyntax, Cloneable, Serializable {
    static final long serialVersionUID = 1848780739976444105L;
    private byte[] m_data;
    public static final byte ASNTYPE = 4;

    public SnmpOctetString() {
        this.m_data = null;
    }

    public SnmpOctetString(final byte[] data) {
        this();
        if (data != null) {
            SnmpUtil.copy(data, 0, this.m_data = new byte[data.length], 0, data.length);
        }
    }

    public SnmpOctetString(final SnmpOctetString second) {
        this(second.m_data);
    }

    public byte[] getString() {
        return this.m_data;
    }

    public void setString(final byte[] data) {
        this.m_data = null;
        if (data != null) {
            SnmpUtil.copy(data, 0, this.m_data = new byte[data.length], 0, data.length);
        }
    }

    public void setString(final String data) {
        this.m_data = null;
        if (data != null) {
            this.m_data = data.getBytes();
        }
    }

    public int getLength() {
        int len = 0;
        if (this.m_data != null) {
            len = this.m_data.length;
        }
        return len;
    }

    public byte typeId() {
        return 4;
    }

    public int encodeASN(final byte[] buf, final int offset, final AsnEncoder encoder) throws AsnEncodingException {
        if (this.m_data == null) {
            throw new AsnEncodingException("No data in octet string");
        }
        return encoder.buildString(buf, offset, this.typeId(), this.m_data);
    }

    public int decodeASN(final byte[] buf, final int offset, final AsnEncoder encoder) throws AsnDecodingException {
        final Object[] rVals = encoder.parseString(buf, offset);
        if ((byte) rVals[1] != this.typeId()) {
            throw new AsnDecodingException("Invalid ASN.1 type");
        }
        this.m_data = (byte[]) rVals[2];
        return (int) rVals[0];
    }

    public SnmpSyntax duplicate() {
        return new SnmpOctetString(this);
    }

    public Object clone() {
        return new SnmpOctetString(this);
    }

    @Override
    public String toString() {
        String rs = null;
        rs = new String(this.m_data);
        return rs;
    }
}
